package com.demo.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioServerChannel {
    public static void main(String[] args) throws IOException {

        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.configureBlocking(false);
        ServerSocket socket = socketChannel.socket();
        SocketAddress address = new InetSocketAddress(8188);
        socket.bind(address);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);//首先注册监听的是连接请求
        System.out.println(socketChannel.hashCode());
        ByteBuffer msg = ByteBuffer.wrap("Hi,I saw you".getBytes());
        for (;;){
            try{
                if(selector.select(1000)<=0){
                    continue;
                };
            }catch (IOException e){
                break;
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()){
                SelectionKey key = it.next();
                it.remove();
                if(key.isAcceptable()){
                    //如果是连接请求
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    System.out.println(server.hashCode());
                    //1.接受此请求
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.write(ByteBuffer.wrap("connected...".getBytes()));
                    //2.监听该channel什么时候可以进行IO操作，同时回复一个连接成功的消息
                    client.register(selector,SelectionKey.OP_READ);
                }
                if(key.isReadable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
                    if(byteBuffer == null){
                        byteBuffer = ByteBuffer.allocate(10);
                    }
                    byteBuffer.clear();
                    System.out.println("receive message:");
                    try{
                        while (channel.read(byteBuffer)>0){
                            byteBuffer.flip();
                            while (byteBuffer.remaining()>0){
                                System.out.print((char)byteBuffer.get());
                            }
                            byteBuffer.clear();
                        }
                        System.out.println();
                        channel.write(msg.duplicate());
                    }catch (IOException e){
                        e.printStackTrace();
                        key.cancel();
                        channel.socket().close();
                        channel.close();
                    }
//                    key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                }
            }
        }
    }
}
